var Data=function(){
    this.init();
};
Data.prototype.init=function () {
    //当页面加载时就会执行下面事件
    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var point = new BMap.Point(112.938003, 28.240463);
    map.centerAndZoom(point, 12);
    map.enableScrollWheelZoom(true);
    var dress = new Map();
    this.dress = dress;//创建map集合
    this.map = map;
    this.findData();
    setInterval(this.findData.bind(this),5*1000);
};
Data.prototype.findData = function () {
    var map = this.map;
    //map.clearOverlays();
    var dress = this.dress;
    var url = "/data";
    var count = 0;
    var that = this;
    $.getJSON(url,function(result){
        that.deleteMarker(result,dress,map);//删除不需要的标注
        for (var i = 0; i < result.length; i++) {
            var up = result[i].latitude;
            var down = result[i].longitude;
            var name = result[i].deviceName;
            var value = result[i].tvalue;
            var time = result[i].updateAt;
            var deviceId = result[i].id;

            if (up == null || down == null) {
                up = 112.938003 + Math.random(0.000001);
                down = 28.240463 + Math.random(0.000001);
                }
                if (value == null) {
                    value = "无";
                }
                if (time == null) {
                    time = "无";
                }
                var point = new BMap.Point(up, down);
                if (!dress.has(deviceId)) {
                    var marker = new BMap.Marker();// 创建标注
                    marker.setPosition(point);//设置标注的地理坐标
                    map.addOverlay(marker);// 将标注添加到地图中
                    var label = new BMap.Label("设备名称:" + name + "  " + "value:" + value + "  " + "时间:" + time,
                        {offset: new BMap.Size(25, -10)});
                    marker.setLabel(label);
                    map.addOverlay(marker);//将标注添加到地图中
                    dress.set(deviceId, marker);//将数据存入Map集合中
                } else {
                    //console.log(dress.get(deviceId));
                    dress.get(deviceId).setPosition(point);
                    map.addOverlay(dress.get(deviceId));
                }
            }

    });
}

//删除不需要的标注的方法
Data.prototype.deleteMarker=function (result,dress,map) {
    //console.log(dress.size);
    for(var [key, value] of dress ) {
        for(var j=0;j<result.length;j++){
            if(key == result[j].id){
                break;
            }
        }
        if(j == result.length){
            //console.log(123456);
            //console.log(key);
            map.removeOverlay(dress.get(key));
        }
    }
}













